package com.suny.reader_writer_lock;

public class Data {
    private final char[] buffer;
    private final ReaderWriterLock lock = new ReaderWriterLock();

    public Data(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        lock.readLock();

        try {
            return doRead();
        } finally {
            lock.readUnLock();
        }
    }

    public void write(char c) throws InterruptedException {
        lock.writeLock();
        try {
            doWrite(c);
        } finally {
            lock.writeUnLock();
        }
    }


    private char[] doRead() {
        char[] newChars = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            newChars[i] = buffer[i];
        }
        slowly();
        return newChars;
    }

    private void doWrite(char c) {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
        }
        slowly();
    }

    private void slowly() {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
    }
}
